//
//  JMTabBarButton.m
//  OpenSesame
//
//  Created by zhangjiaming on 15/12/21.
//  Copyright © 2015年 OpenSesame. All rights reserved.
//

#import "JMTabBarButton.h"

@implementation JMTabBarButton

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // 设置图片居中
        self.imageView.contentMode = UIViewContentModeCenter;
    }
    return self;
}

/**
 *  去掉父类在高亮时所做的操作
 */
- (void)setHighlighted:(BOOL)highlighted {}

- (void)setItem:(UITabBarItem *)item {
    _item = item;
    // 利用KVO监听属性的改变
    [item addObserver:self forKeyPath:@"image" options:NSKeyValueObservingOptionNew context:nil];
    [item addObserver:self forKeyPath:@"selectedImage" options:NSKeyValueObservingOptionNew context:nil];
    
    // 属性赋值
    [self observeValueForKeyPath:nil ofObject:nil change:nil context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    [self setImage:self.item.image forState:UIControlStateNormal];
    [self setImage:self.item.selectedImage forState:UIControlStateSelected];
}

/**
 *  KVO监听必须在监听器释放的时候，移除监听操作
 */
- (void)dealloc {
    [self.item removeObserver:self forKeyPath:@"image"];
    [self.item removeObserver:self forKeyPath:@"selectedImage"];
}
@end
